/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CriarUsuario.java
 *
 * Created on 01/05/2011, 01:45:36
 */
package Interface;

import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import ludi.Curso;
import ludi.Usuario;
import ludiExcecoes.GUILudi;
import ludiExcecoes.UsuarioExcecao;
import utils.BancoDeDados;

/**
 *
 * @author alison
 */
public class CriarUsuario extends javax.swing.JInternalFrame {

    BancoDeDados banco;
    Usuario usuario;
    Usuario editUser;
    /** Creates new form CriarUsuario */
    public CriarUsuario(BancoDeDados banco, Usuario usuario, Usuario editUser) {
        this.banco = banco;
        this.usuario = usuario;
        this.editUser = editUser;
        initComponents();

        if (editUser == null){
            radioCurso.setSelected(true);
            botaoAlterar.setEnabled(false);
            botaoExcluir.setEnabled(false);
        } else{
            campoLogin.setText(editUser.getLogin());
            campoSenha.setText(editUser.getSenha());
            campoConfirmarSenha.setText(editUser.getSenha());
            campoNome.setText(editUser.getNome());
            campoEmail.setText(editUser.getEmail());
            campoConfirmarEmail.setText(editUser.getEmail());
            botaoCadastrar.setEnabled(false);
            campoLogin.setEnabled(false);
            if (editUser.getPermissoes() == 1){
                radioAdministrador.setSelected(true);
                radioAdministrador.setEnabled(false);
                radioCurso.setEnabled(false);
                seletorUnidade.setVisible(false);
                labelUnidade.setVisible(false);
                if (usuario.getLogin().equals(editUser.getLogin())){
                    botaoExcluir.setEnabled(false);
                }
            } else{
                radioCurso.setSelected(true);
                radioAdministrador.setEnabled(false);
                radioCurso.setEnabled(false);
                try {
                    seletorUnidade.setSelectedItem(banco.getCurso(editUser.getLogin()).getUnidade());
                } catch (SQLException ex) {
                    Logger.getLogger(CriarUsuario.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        
        this.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        grupoBotaoTipoUsuario = new javax.swing.ButtonGroup();
        labelLogin = new javax.swing.JLabel();
        campoLogin = new javax.swing.JTextField();
        labelSenha = new javax.swing.JLabel();
        labelConfirmarSenha = new javax.swing.JLabel();
        labelNome = new javax.swing.JLabel();
        campoNome = new javax.swing.JTextField();
        labelUnidade = new javax.swing.JLabel();
        campoEmail = new javax.swing.JTextField();
        labelEmail = new javax.swing.JLabel();
        labelTipoUsuario = new javax.swing.JLabel();
        labelConfirmarEmail = new javax.swing.JLabel();
        campoConfirmarEmail = new javax.swing.JTextField();
        campoSenha = new javax.swing.JPasswordField();
        campoConfirmarSenha = new javax.swing.JPasswordField();
        botaoCadastrar = new javax.swing.JButton();
        botaoCancelar = new javax.swing.JButton();
        seletorUnidade = new javax.swing.JComboBox();
        radioCurso = new javax.swing.JRadioButton();
        radioAdministrador = new javax.swing.JRadioButton();
        botaoAlterar = new javax.swing.JButton();
        botaoExcluir = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setTitle("Cadastrar Usuário");

        labelLogin.setText("Login");

        campoLogin.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                campoLoginCaretUpdate(evt);
            }
        });

        labelSenha.setText("Senha");

        labelConfirmarSenha.setText("Confimar Senha");

        labelNome.setText("Nome");

        campoNome.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                campoNomeCaretUpdate(evt);
            }
        });

        labelUnidade.setText("Unidade Acadêmica");

        campoEmail.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                campoEmailCaretUpdate(evt);
            }
        });

        labelEmail.setText("E-mail");

        labelTipoUsuario.setText("Tipo de Usuário");

        labelConfirmarEmail.setText("Confimar e-mail");

        campoConfirmarEmail.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                campoConfirmarEmailCaretUpdate(evt);
            }
        });

        campoSenha.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                campoSenhaCaretUpdate(evt);
            }
        });
        campoSenha.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                campoSenhaFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoSenhaFocusLost(evt);
            }
        });
        campoSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                campoSenhaKeyTyped(evt);
            }
        });

        campoConfirmarSenha.addCaretListener(new javax.swing.event.CaretListener() {
            public void caretUpdate(javax.swing.event.CaretEvent evt) {
                campoConfirmarSenhaCaretUpdate(evt);
            }
        });
        campoConfirmarSenha.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                campoConfirmarSenhaFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                campoConfirmarSenhaFocusLost(evt);
            }
        });
        campoConfirmarSenha.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                campoConfirmarSenhaKeyTyped(evt);
            }
        });

        botaoCadastrar.setText("Cadastrar");
        botaoCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCadastrarActionPerformed(evt);
            }
        });

        botaoCancelar.setText("Cancelar");
        botaoCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCancelarActionPerformed(evt);
            }
        });

        seletorUnidade.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "EEM", "FACED", "FAO", "FAPSI", "FCA", "FCF", "FD", "FEF", "FES", "FM", "FT", "IAA", "ICB", "ICE", "ICET", "ICHL", "ICSEZ", "INCBC", "ISB" }));

        grupoBotaoTipoUsuario.add(radioCurso);
        radioCurso.setText("Curso");
        radioCurso.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                radioCursoStateChanged(evt);
            }
        });

        grupoBotaoTipoUsuario.add(radioAdministrador);
        radioAdministrador.setText("Administrador");

        botaoAlterar.setText("Alterar");
        botaoAlterar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoAlterarActionPerformed(evt);
            }
        });

        botaoExcluir.setText("Excluir");
        botaoExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoExcluirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(labelConfirmarSenha)
                                    .addComponent(labelLogin)
                                    .addComponent(labelSenha))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(campoSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                                    .addComponent(campoLogin, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                                    .addComponent(campoConfirmarSenha, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(labelEmail)
                                        .addComponent(labelNome))
                                    .addComponent(labelConfirmarEmail))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(campoEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                                    .addComponent(campoConfirmarEmail, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                                    .addComponent(campoNome, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(labelUnidade)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(seletorUnidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(labelTipoUsuario)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(radioAdministrador)
                                .addGap(18, 18, 18)
                                .addComponent(radioCurso)))
                        .addGap(27, 27, 27))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(botaoCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botaoExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botaoAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(botaoCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelLogin))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelSenha)
                    .addComponent(campoSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelConfirmarSenha)
                    .addComponent(campoConfirmarSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelNome)
                    .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelEmail)
                    .addComponent(campoEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(campoConfirmarEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelConfirmarEmail))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelTipoUsuario)
                    .addComponent(radioAdministrador)
                    .addComponent(radioCurso))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(seletorUnidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelUnidade))
                .addGap(18, 18, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(botaoCadastrar)
                    .addComponent(botaoAlterar)
                    .addComponent(botaoExcluir)
                    .addComponent(botaoCancelar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCancelarActionPerformed
        this.dispose();
    }//GEN-LAST:event_botaoCancelarActionPerformed

    private void campoLoginCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_campoLoginCaretUpdate
          String text = campoLogin.getText();
          int max = 9;
          if (text.length() > max) {
            text = text.substring (0, max);
              campoLogin.setText (text);
          }
    }//GEN-LAST:event_campoLoginCaretUpdate

    private void campoSenhaCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_campoSenhaCaretUpdate
          validaSenha();
    }//GEN-LAST:event_campoSenhaCaretUpdate

    private void campoSenhaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_campoSenhaFocusGained
        validaSenha();
    }//GEN-LAST:event_campoSenhaFocusGained

    private void campoSenhaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_campoSenhaFocusLost
        validaSenha();
    }//GEN-LAST:event_campoSenhaFocusLost

    private void campoSenhaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoSenhaKeyTyped
        validaSenha();
    }//GEN-LAST:event_campoSenhaKeyTyped

    private void campoConfirmarSenhaCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_campoConfirmarSenhaCaretUpdate
        validaSenha2();
    }//GEN-LAST:event_campoConfirmarSenhaCaretUpdate

    private void campoConfirmarSenhaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_campoConfirmarSenhaFocusGained
        validaSenha2();
    }//GEN-LAST:event_campoConfirmarSenhaFocusGained

    private void campoConfirmarSenhaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_campoConfirmarSenhaFocusLost
        validaSenha2();
    }//GEN-LAST:event_campoConfirmarSenhaFocusLost

    private void campoConfirmarSenhaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_campoConfirmarSenhaKeyTyped
        validaSenha2();
    }//GEN-LAST:event_campoConfirmarSenhaKeyTyped

    private void campoNomeCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_campoNomeCaretUpdate
          String text = campoNome.getText();
          int max = 49;
          if (text.length() > max) {
            text = text.substring (0, max);
              campoNome.setText (text);
          }
    }//GEN-LAST:event_campoNomeCaretUpdate

    private void campoEmailCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_campoEmailCaretUpdate
          String text = campoEmail.getText();
          int max = 49;
          if (text.length() > max) {
            text = text.substring (0, max);
              campoEmail.setText (text);
          }
    }//GEN-LAST:event_campoEmailCaretUpdate

    private void campoConfirmarEmailCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_campoConfirmarEmailCaretUpdate
          String text = campoConfirmarEmail.getText();
          int max = 49;
          if (text.length() > max) {
            text = text.substring (0, max);
              campoConfirmarEmail.setText (text);
          }
    }//GEN-LAST:event_campoConfirmarEmailCaretUpdate

    private void radioCursoStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_radioCursoStateChanged
        if(radioCurso.isSelected()){
            labelUnidade.setVisible(true);
            seletorUnidade.setVisible(true);
        }
         else{
            labelUnidade.setVisible(false);
            seletorUnidade.setVisible(false);
        }
    }//GEN-LAST:event_radioCursoStateChanged

    private void botaoCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoCadastrarActionPerformed

        try {
            Usuario usuario = verificaDados();
            if (radioAdministrador.isSelected()){
                banco.insereUsuario(usuario);
            } else{
                banco.insereCurso((Curso) usuario);
            }
            JOptionPane.showMessageDialog(this, "Usuário cadastrado com sucesso!", "Cadastrar Usuário", JOptionPane.INFORMATION_MESSAGE);
            //fecha a janela
            this.dispose();
        }  catch (UsuarioExcecao e) {
			if (e.getLocalizedMessage().equals("Usuario ja cadastrado")){
				JOptionPane.showMessageDialog(this, "Usuário já está cadastrado!", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);			
			}
			e.printStackTrace();
		}  catch (SQLException ex) {
            Logger.getLogger(CriarUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }  catch (GUILudi ex) {
            Logger.getLogger(CriarUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_botaoCadastrarActionPerformed

    private Usuario verificaDados() throws GUILudi{
        if (!(new String(campoSenha.getPassword())).equals(new String(campoConfirmarSenha.getPassword()))){
            JOptionPane.showMessageDialog(this, "Senhas não correspondem!", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);
            throw new GUILudi("Dados invalidos!");
        }
        if (!(campoEmail.getText().equals(campoConfirmarEmail.getText()))){
            JOptionPane.showMessageDialog(this, "E-mails não correspondem!", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);
            throw new GUILudi("Dados invalidos!");
        }
        if (campoLogin.getText().equals("")){
            JOptionPane.showMessageDialog(this, "Login não pode ficar em branco!", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);
            throw new GUILudi("Dados invalidos!");
        }
        if ((new String(campoSenha.getPassword()).equals(""))){
            JOptionPane.showMessageDialog(this, "Senha não pode ficar em branco!", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);
            throw new GUILudi("Dados invalidos!");
        }
        if (campoEmail.getText().equals("")){
            JOptionPane.showMessageDialog(this, "E-mail não pode ficar em branco!", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);
            throw new GUILudi("Dados invalidos!");
        }
        if (campoNome.getText().equals("")){
            JOptionPane.showMessageDialog(this, "Nome não pode ficar em branco!", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);
            throw new GUILudi("Dados invalidos!");
        }

        int permissao = radioAdministrador.isSelected() ? 1 : 2;
        String unidade = radioAdministrador.isSelected() ? "": (String) seletorUnidade.getSelectedItem();
        Usuario usuario = new Curso(permissao, campoLogin.getText(), new String(campoSenha.getPassword()),
                                                campoNome.getText(), campoEmail.getText(), unidade);

        return usuario;
    }


    private void botaoAlterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoAlterarActionPerformed
        try {
            Usuario usuario = verificaDados();
            if (radioAdministrador.isSelected()){
                banco.setUsuario(usuario);
            } else{
                banco.setCurso((Curso) usuario);
            }
            JOptionPane.showMessageDialog(this, "Usuário alterado com sucesso!", "Cadastrar Usuário", JOptionPane.INFORMATION_MESSAGE);

            this.dispose();
        } catch (SQLException ex) {
            Logger.getLogger(CriarUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (GUILudi ex) {
            Logger.getLogger(CriarUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UsuarioExcecao ex){
            if (ex.getLocalizedMessage().equals("Erro ao alterar unidade academica: Ainda ha atletas neste curso")){
                JOptionPane.showMessageDialog(this, "Erro ao alterar unidade acadêmica deste curso.\nNão pode haver atletas cadastrados neste curso\npara realizar a operação de mudar a unidade acadêmica.", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);
	    }
            if (ex.getLocalizedMessage().equals("Erro ao alterar unidade academica: Ainda ha times neste curso")){
		JOptionPane.showMessageDialog(this, "Erro ao alterar unidade acadêmica deste curso.\nNão pode haver times cadastrados neste curso\npara realizar a operação de mudar a unidade acadêmica.", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);
            }
            ex.printStackTrace();
        }
    }//GEN-LAST:event_botaoAlterarActionPerformed

    private void botaoExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoExcluirActionPerformed
        try {
            if (editUser.getPermissoes() == 1){
                banco.deleteUsuario(editUser);
            } else{
                banco.deleteCurso(banco.getCurso(editUser.getLogin()));
            }
            JOptionPane.showMessageDialog(this, "Usuário excluído com sucesso!", "Cadastrar Usuário", JOptionPane.INFORMATION_MESSAGE);
            this.dispose();
        } catch (SQLException ex) {
                Logger.getLogger(CriarUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UsuarioExcecao e) {
		if (e.getLocalizedMessage().equals("Ainda ha atletas neste curso")){
			JOptionPane.showMessageDialog(this, "Exclua os atletas deste curso antes de excluí-lo", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);			
		}
		if (e.getLocalizedMessage().equals("Ainda ha times neste curso")){
			JOptionPane.showMessageDialog(this, "Exclua os times deste curso antes de excluí-lo", "Cadastrar Usuário", JOptionPane.ERROR_MESSAGE);			
		}			
		e.printStackTrace();
        }
    }//GEN-LAST:event_botaoExcluirActionPerformed

    private void validaSenha(){
          String text = new String(campoSenha.getPassword());
          int max = 19;
          if (text.length() > max) {
            text = text.substring (0, max);
              campoSenha.setText(text);
          }
    }

        private void validaSenha2(){
          String text = new String(campoConfirmarSenha.getPassword());
          int max = 19;
          if (text.length() > max) {
            text = text.substring (0, max);
              campoConfirmarSenha.setText(text);
          }
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botaoAlterar;
    private javax.swing.JButton botaoCadastrar;
    private javax.swing.JButton botaoCancelar;
    private javax.swing.JButton botaoExcluir;
    private javax.swing.JTextField campoConfirmarEmail;
    private javax.swing.JPasswordField campoConfirmarSenha;
    private javax.swing.JTextField campoEmail;
    private javax.swing.JTextField campoLogin;
    private javax.swing.JTextField campoNome;
    private javax.swing.JPasswordField campoSenha;
    private javax.swing.ButtonGroup grupoBotaoTipoUsuario;
    private javax.swing.JLabel labelConfirmarEmail;
    private javax.swing.JLabel labelConfirmarSenha;
    private javax.swing.JLabel labelEmail;
    private javax.swing.JLabel labelLogin;
    private javax.swing.JLabel labelNome;
    private javax.swing.JLabel labelSenha;
    private javax.swing.JLabel labelTipoUsuario;
    private javax.swing.JLabel labelUnidade;
    private javax.swing.JRadioButton radioAdministrador;
    private javax.swing.JRadioButton radioCurso;
    private javax.swing.JComboBox seletorUnidade;
    // End of variables declaration//GEN-END:variables
}
